package org.zyj.io;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 *
 */
public class NettyIO_3 {

    public static void main(String[] args) throws InterruptedException {
        //即使这里传入了99, 会创建99个EventLoop对象, 但是线程被使用的只有一个, 也就是说只有一个线程处理ACCEPT事件
        NioEventLoopGroup boss = new NioEventLoopGroup(99);
        //20个线程用来处理读写事件
        NioEventLoopGroup worker = new NioEventLoopGroup(20);
        ServerBootstrap boot = new ServerBootstrap();
        boot.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        pipeline.addLast(new MyInbound());
                    }
                });
        ChannelFuture future = boot.bind(8080).sync();
        future.channel().closeFuture().sync();
    }

    static class MyInbound extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ctx.write(msg);//echo的作用, 将读到的东西,写回客户端
        }

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            ctx.flush();
        }
    }

}
